# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import sys

import reactivex as rx
from reactivex import operators as ops
from reactivex import Observable, from_callable, throw
import json
import requests

"""文件地址"""
filePath = sys.argv[1]


# filePath = "sys.argv[1]"


def fetch_user():
    # 登录URL
    login_url = f'https://app.shanggewangwl.com/api/user/login'  # 替换为实际的登录URL

    # 登录所需的表单数据
    payload = json.dumps({
        "username": "admin",
        "password": "admin"
    })

    # 自定义请求头（根据实际情况调整）
    headers = {
        "Accept": "application/json",
        'Content-Type': 'application/json',
        # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        # 'Referer': 'https://example.com/login',  # 替换为登录页面的URL
        # 可能需要添加其他头部信息
    }

    # def subscribe(observer, scheduler=None):
    #     response = requests.post(url=login_url, headers=headers, data=payload)
    #     print("response------------------"+response.text)
    #     observer.on_next(response.json())
    #     observer.on_completed()
    #
    # return Observable(subscribe)
    return from_callable(
        lambda: requests.post(
            url=login_url,
            data=payload,  # 如果是表单数据用data
            # 如果网站使用JSON格式，改用json参数:
            # json=login_data,
            headers=headers,
            # 如果需要保持会话，可以添加cookies或使用Session
            # cookies=cookies,
            # 如果需要验证SSL证书，verify=True
            # verify=False  # 仅用于测试，生产环境应该设为True或指定证书路径
        )
    )


def upload_file(token, file_path, teamId):
    upload_url = f"https://app.shanggewangwl.com/api/apps/{teamId}/upload"

    request_headers = {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + token,
    }

    def subscribe(observer, scheduler=None):
        try:

            with open(file_path, 'rb') as f:
                files = {'file': f}
                response = requests.post(url=upload_url, headers=request_headers, files=files)
                observer.on_next(response.json())
                observer.on_completed()
        except Exception as e:
            observer.on_error(e)

    return Observable(subscribe)


def publish(token, teamId, result):
    app_id = result['data']['version']['appId']
    version_Id = result['data']['version']['_id']
    version_Code = result['data']['version']['_id']
    appName = result['data']['app']['appName']

    # 登录URL
    login_url = f'https://app.shanggewangwl.com/api/apps/{teamId}/{app_id}/release'  # 替换为实际的登录URL

    # 登录所需的表单数据
    request_headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token,
    }

    payload = json.dumps({
        "versionId": version_Id,
        "release": True,
        "versionCode": version_Code
    })

    def subscribe(observer, scheduler=None):
        try:
            response = requests.post(
                url=login_url,
                # 如果网站使用JSON格式，改用json参数:
                # json=login_data,
                headers=request_headers,
                data=payload,
            )

            print(appName, "--已发布")
            observer.on_next(response.json())
            observer.on_completed()
        except Exception as e:
            observer.on_error(e)

    return Observable(subscribe)


# 1. 提取关键逻辑为独立函数（增强可读性）
def get_user_token_and_team(user):
    """提取用户token和最后一个team的ID"""

    # print(user.status_code)  # 获取响应状态码
    # print(user.headers)  # 获取响应头
    json_data = json.loads(user.content)

    try:
        token = json_data['data']['token']
        for index, item in enumerate(json_data['data']['teams']):
            print(str(index) + "、" + item['name'])

        while True:
            user_input = input("请选择目标群组: ")
            if int(user_input) < len(json_data['data']['teams']):
                break
            print("输入无效，请重新输入！")

        last_team_id = json_data['data']['teams'][int(user_input)]["_id"]
        return token, last_team_id
    except (KeyError, IndexError) as e:
        raise ValueError(f"Invalid user data structure: {e}")


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'\n--- Hello,{name}. 又是开心的时刻 ---\n')  # Press Ctrl+F8 to toggle the breakpoint.
    # 获取用户信息及其帖子
    # fetch_user().pipe(ops.flat_map(lambda user: print(user.json())),
    #                   ).subscribe(on_next=lambda data: print(data.json()),
    #                               on_error=lambda error: print(error),
    #                               on_completed=lambda: print("complete"))
    # return
    # 2. 使用更清晰的管道操作
    fetch_user().pipe(
        ops.flat_map(lambda user:
                     from_callable(lambda: get_user_token_and_team(user)).pipe(
                         ops.flat_map(lambda token_team:
                                      upload_file(
                                          token=token_team[0],
                                          file_path=filePath,
                                          teamId=token_team[1]
                                      ).pipe(
                                          ops.flat_map(lambda upload_result:
                                                       publish(token_team[0], token_team[1], upload_result)
                                                       if upload_result['success'] else throw(
                                                           ValueError(upload_result['message'])
                                                       ))
                                      )),
                         ops.catch(lambda error, _: throw(f"错误信息: {error}"))
                     ))
    ).subscribe(
        on_next=lambda data: print(f"success: {data}"),
        on_error=lambda e: print(f"Error: {e}"),
        on_completed=lambda: print("Operation completed\n")
    )


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('Baby')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
